<template>
  <div class="storage-manager">
    <div class="storage-tabs">
      <button
          v-for="tab in storageTypes"
          :key="tab"
          :class="['tab-button', { 'active': activeTab === tab }]"
          @click="switchTab(tab)"
      >
        {{ tab }}
        <span class="tab-badge">{{ itemCounts[tab] || 0 }}</span>
      </button>
    </div>

    <div class="storage-content">
      <div class="storage-controls">
        <div class="search-container">
          <i class="icon-search"></i>
          <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索键名..."
              class="search-input"
              @keyup.enter="focusFirstItem"
          >
          <button
              v-if="searchQuery"
              class="clear-search"
              @click="searchQuery = ''"
          >
            <i class="icon-close"></i>
          </button>
        </div>

        <div class="button-group">
          <button class="btn primary" @click="addNewItem">
            <i class="icon-add"></i> 添加
          </button>
          <button class="btn secondary" @click="refreshStorage">
            <i class="icon-refresh"></i> 刷新
          </button>
          <button
              class="btn danger"
              @click="showMessageDialog"
              :disabled="Object.keys(filteredItems).length === 0"
          >
            <i class="icon-clear"></i> 清空
          </button>
        </div>
      </div>

      <div class="storage-items" ref="itemsContainer">
        <div
            v-for="(value, key) in filteredItems"
            :key="key"
            :class="['storage-item', { 'selected': selectedKey === key }]"
            @click="selectItem(key)"
            @dblclick="editItem(key)"
        >
          <div class="item-key">{{ key }}</div>
          <div class="item-value">{{ formatValue(value) }}</div>
          <div class="item-actions">
            <button class="item-btn edit" @click.stop="editItem(key)">
              <i class="icon-edit"></i>
            </button>
            <button class="item-btn delete" @click.stop="deleteItem(key)">
              <i class="icon-delete"></i>
            </button>
          </div>
        </div>
        <div v-if="Object.keys(filteredItems).length === 0" class="empty-message">
          <i class="icon-empty"></i>
          <p>{{ searchQuery ? '没有找到匹配的存储项' : '当前存储为空' }}</p>
          <button v-if="searchQuery" class="btn secondary" @click="searchQuery = ''">
            清除搜索条件
          </button>
        </div>
      </div>
    </div>

    <StorageEditDialog
        :visible="showEditDialog"
        :title="editDialogTitle"
        :storageItem="currentEditItem"
        :isEditMode="isEditMode"
        @save="handleSave"
        @delete="handleDelete"
        @close="closeEditDialog"
    />
    <BaseModal
        :visible="messageDialogVisible"
        title="警告"
        @cancel="closeMessageDialog"
        @confirm="clearStorage"
    >
      <div>
        是否清空 {{ activeTab }}
      </div>
    </BaseModal>
  </div>
</template>

<script>
import StorageEditDialog from './StorageEditDialog.vue'
import BaseModal from "@/components/BaseModal.vue";

export default {
  components: {
    BaseModal,
    StorageEditDialog
  },
  data() {
    return {
      storageTypes: ['localStorage', 'sessionStorage'],
      activeTab: 'localStorage',
      searchQuery: '',
      showEditDialog: false,
      selectedKey: null,
      currentEditItem: {
        key: '',
        value: '',
        type: 'local'
      },
      isEditMode: false,
      items: {},
      itemCounts: {},
      messageDialogVisible: false,
    }
  },
  computed: {
    filteredItems() {
      const items = this.items[this.activeTab] || {}
      if (!this.searchQuery) return items

      return Object.fromEntries(
          Object.entries(items).filter(([key]) =>
              key.toLowerCase().includes(this.searchQuery.toLowerCase())
          )
      )
    },
    editDialogTitle() {
      return this.isEditMode ? '编辑存储项' : '添加新存储项'
    }
  },
  watch: {
    activeTab() {
      this.loadStorageItems()
    },
    items: {
      deep: true,
      handler() {
        this.updateItemCounts()
      }
    }
  },
  mounted() {
    this.loadStorageItems()
    window.addEventListener('storage', this.handleStorageEvent)
    this.updateItemCounts()
  },
  beforeUnmount() {
    window.removeEventListener('storage', this.handleStorageEvent)
  },
  methods: {
    async loadStorageItems() {
      try {
        const storage = window[this.activeTab]
        const items = {}

        for (let i = 0; i < storage.length; i++) {
          const key = storage.key(i)
          items[key] = storage.getItem(key)
        }

        this.items = {
          ...this.items,
          [this.activeTab]: items
        }
        this.selectedKey = null
      } catch (error) {
        console.error('加载存储项失败:', error)
      }
    },
    formatValue(value) {
      try {
        const parsed = JSON.parse(value)
        return typeof parsed === 'object' ? JSON.stringify(parsed, null, 2) : value
      } catch {
        return value
      }
    },
    switchTab(tab) {
      this.activeTab = tab
      this.searchQuery = ''
    },
    addNewItem() {
      this.currentEditItem = {
        key: '',
        value: '',
        type: this.activeTab === 'localStorage' ? 'local' : 'session'
      }
      this.isEditMode = false
      this.showEditDialog = true
    },
    selectItem(key) {
      this.selectedKey = this.selectedKey === key ? null : key
    },
    editItem(key) {
      this.currentEditItem = {
        key: key,
        value: this.items[this.activeTab][key],
        type: this.activeTab === 'localStorage' ? 'local' : 'session'
      }
      this.isEditMode = true
      this.showEditDialog = true
    },
    async deleteItem(key) {
      if (await this.$confirm(`确定要删除 "${key}" 吗?`)) {
        try {
          window[this.activeTab].removeItem(key)
          this.loadStorageItems()
          this.$notify.success('删除成功')
        } catch (error) {
          console.error('删除失败:', error)
          this.$notify.error('删除失败')
        }
      }
    },
    showMessageDialog() {
      this.messageDialogVisible = true
    },
    closeMessageDialog() {
      this.messageDialogVisible = false
    },
    async clearStorage() {
      try {
        window[this.activeTab].clear()
        await this.loadStorageItems()
        this.closeMessageDialog()
      } catch (error) {
        alert('清空失败')
      }
    },
    handleSave({ key, value, type }) {
      const storageType = type === 'local' ? 'localStorage' : 'sessionStorage'

      try {
        if (this.isEditMode && this.currentEditItem.key !== key) {
          window[storageType].removeItem(this.currentEditItem.key)
        }

        window[storageType].setItem(key, value)
        this.loadStorageItems()
        this.showEditDialog = false
        this.$notify.success(this.isEditMode ? '更新成功' : '添加成功')
      } catch (error) {
        console.error('保存失败:', error)
        this.$notify.error('保存失败')
      }
    },
    handleDelete({ key, type }) {
      const storageType = type === 'local' ? 'localStorage' : 'sessionStorage'
      window[storageType].removeItem(key)
      this.loadStorageItems()
      this.showEditDialog = false
      this.$notify.success('删除成功')
    },
    refreshStorage() {
      this.loadStorageItems()
      this.$notify.info('已刷新')
    },
    handleStorageEvent(event) {
      if (event.storageArea === window[this.activeTab]) {
        this.loadStorageItems()
      }
    },
    closeEditDialog() {
      this.showEditDialog = false
    },
    updateItemCounts() {
      this.storageTypes.forEach(tab => {
        this.itemCounts[tab] = Object.keys(this.items[tab] || {}).length
      })
    },
    focusFirstItem() {
      if (this.$refs.itemsContainer && this.filteredItems.length > 0) {
        const firstItem = this.$refs.itemsContainer.querySelector('.storage-item')
        if (firstItem) firstItem.focus()
      }
    },
  }
}
</script>

<style scoped>
/* 更新后的样式 */
.storage-manager {
  --primary-color: #00ff87;
  --secondary-color: #ff1f71;
  --accent-color: #60efff;
  --danger-color: #ff4757;
  --bg-dark: rgba(10, 20, 30, 0.95);
  --bg-light: rgba(255, 255, 255, 0.1);
  --text-primary: rgba(255, 255, 255, 0.9);
  --text-secondary: rgba(255, 255, 255, 0.7);
  --border-color: rgba(255, 255, 255, 0.2);
  --highlight-color: rgba(0, 255, 135, 0.1);
  --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  background: var(--bg-dark);
  border-radius: 12px;
  border: 1px solid var(--border-color);
  color: var(--text-primary);
  font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.storage-tabs {
  display: flex;
  border-bottom: 1px solid var(--border-color);
  background: rgba(0, 0, 0, 0.2);
}

.tab-button {
  flex: 1;
  padding: 12px;
  background: none;
  border: none;
  color: var(--text-secondary);
  font-weight: 600;
  cursor: pointer;
  transition: var(--transition);
  border-bottom: 2px solid transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  position: relative;
}

.tab-button:hover {
  background: rgba(255, 255, 255, 0.05);
}

.tab-button.active {
  color: var(--primary-color);
  border-bottom-color: var(--primary-color);
}

.tab-badge {
  background: var(--primary-color);
  color: #111;
  font-size: 0.7rem;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: bold;
}

.storage-content {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.storage-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  align-items: center;
}

.search-container {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
}

.search-container .icon-search {
  position: absolute;
  left: 12px;
  color: var(--text-secondary);
}

.search-input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  background: var(--bg-light);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  color: var(--text-primary);
  font-family: inherit;
  transition: var(--transition);
}

.search-input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(0, 255, 135, 0.2);
}

.clear-search {
  position: absolute;
  right: 10px;
  background: none;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: 2px;
}

.clear-search:hover {
  color: var(--secondary-color);
}

.button-group {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-family: inherit;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: var(--transition);
}

.btn.primary {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--accent-color) 100%);
  color: #111;
}

.btn.secondary {
  background: var(--bg-light);
  color: var(--text-primary);
}

.btn.danger {
  background: linear-gradient(135deg, var(--danger-color) 0%, #ff6b81 100%);
  color: white;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.storage-items {
  flex: 1;
  overflow-y: auto;
  border-radius: 6px;
  background: rgba(0, 0, 0, 0.1);
}

.storage-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  margin-bottom: 6px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: var(--transition);
  position: relative;
}

.storage-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.storage-item.selected {
  background: var(--highlight-color);
  border-left: 3px solid var(--primary-color);
}

.item-key {
  flex: 1;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 10px;
}

.item-value {
  flex: 2;
  color: var(--text-secondary);
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-family: monospace;
}

.item-actions {
  display: flex;
  gap: 8px;
  margin-left: 10px;
  opacity: 0;
  transition: var(--transition);
}

.storage-item:hover .item-actions {
  opacity: 1;
}

.item-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-btn.edit {
  color: var(--accent-color);
}

.item-btn.delete {
  color: var(--secondary-color);
}

.item-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.empty-message {
  padding: 40px 20px;
  text-align: center;
  color: var(--text-secondary);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-message .icon-empty {
  font-size: 3rem;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-message p {
  margin-bottom: 20px;
}

/* 图标样式 */
.icon-search,
.icon-add,
.icon-refresh,
.icon-delete,
.icon-edit,
.icon-clear,
.icon-empty,
.icon-close {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.icon-search {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ffffff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z' /%3E%3C/svg%3E");
}

.icon-add {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23111'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M12 4v16m8-8H4' /%3E%3C/svg%3E");
}

.icon-refresh {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ffffff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15' /%3E%3C/svg%3E");
}

.icon-delete {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ff1f71'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16' /%3E%3C/svg%3E");
}

.icon-edit {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2360efff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z' /%3E%3C/svg%3E");
}

.icon-clear {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ffffff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16' /%3E%3C/svg%3E");
}

.icon-empty {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ffffff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='1' d='M20 12H4m16 0l-4-4m4 4l-4 4' /%3E%3C/svg%3E");
  opacity: 0.5;
}

.icon-close {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%23ffffff'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M6 18L18 6M6 6l12 12' /%3E%3C/svg%3E");
}

/* 滚动条样式 */
.storage-items::-webkit-scrollbar {
  width: 8px;
}

.storage-items::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
}

.storage-items::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.storage-items::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

@media (max-width: 768px) {
  .storage-controls {
    flex-direction: column;
    gap: 10px;
  }

  .search-container {
    width: 100%;
  }

  .button-group {
    width: 100%;
    justify-content: flex-end;
  }

  .storage-item {
    flex-direction: column;
    align-items: flex-start;
    padding: 10px;
  }

  .item-value {
    margin-top: 5px;
    width: 100%;
  }

  .item-actions {
    position: absolute;
    right: 10px;
    top: 10px;
    opacity: 1;
  }
}
</style>
